package com.xcl.controller;

import com.xcl.service.WaybillServiceInter;
import com.xcl.service.XclTailAfterServiceInter;
import com.xcl.util.RegionUtil;
import com.zzg.entity.*;
import com.zzg.util.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName WaybillController
 * @Description 运单管理控制器
 * @Author: xiaochaolei
 * @date 2021/6/21 10:32
 * @Version 1. 0
 */
@Controller
public class WaybillController {
    @Autowired
    WaybillServiceInter waybillServiceInter;


    @Autowired
    XclTailAfterServiceInter xclTailAfter;
    /**
     * 得到所有的分站
     * @return json格式的分站集合
     */
    @PostMapping(value = "/getAllSubstation",produces = "application/json;charset=utf-8")
    @ResponseBody
    public List<Substation> getAllSubstation(HttpServletRequest request){
        //得到所有的分站
        List<Substation> substations=waybillServiceInter.getAllSubstation();
        //将id设置到负责人中
        //substations.get(0).setPrincipal(UuidUtil.getUuid());
        List<String> strings = new ArrayList<>();
        strings.add(UuidUtil.getUuid());
        strings.add(UuidUtil.getUuid());
        substations.get(0).setNumeric(strings);


        //返回
        return substations;
    }

    /**
     * 查询托运单号是否存在
     * @param id
     * @return
     */
    @PostMapping(value = "/getWaybillById",produces = "application/json;charset=utf-8")
    @ResponseBody
    public Waybill getWaybillById(String id){
        //判断是否存在过
        Waybill substation=waybillServiceInter.getWaybillById(id);
        return substation;
    }



    /**
     * 根据收货人名字得到收货人的信息
     * @return 收货人集合
     */
    @PostMapping(value = "/getAllConsigneeByClientname",produces = "application/json;charset=utf-8")
    @ResponseBody
    public  Map<String,Object> getAllConsigneeByClientname(){
        Map<String,Object> map = new HashMap<>();
        map.put("data",waybillServiceInter.getAllConsigneeByClientname());
        map.put("index",3);
        //返回map集合
        return map;
    }


    /**
     * 根据收货人电话得到收货人的信息
     * @return 收货人集合
     */
    @PostMapping(value = "/getAllConsigneeByPhone",produces = "application/json;charset=utf-8")
    @ResponseBody
    public   Map<String,Object> getAllConsigneeByPhone(){
        Map<String,Object> map = new HashMap<>();
        map.put("data",waybillServiceInter.getAllConsigneeByPhone());
        map.put("index",2);
        //返回map集合
        return map;
    }


    /**
     * 根据收货人id得到收货人的信息
     * @return 收货人对象
     */
    @PostMapping(value = "/getAllConsigneeByConsigneeId",produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String,Object> getAllConsigneeByConsigneeId(String id){
        Map<String,Object> map = new HashMap<>();
        System.out.println("id:"+id);
        map.put("type","收货人");
        map.put("data", waybillServiceInter.getAllConsigneeByConsigneeId(id));
        //返回map集合
        return map;
    }


    /**
     * 根据发货人名字得到发货人的信息
     * @return 发货人集合
     */
    @PostMapping(value = "/getAllConsignerByClientname",produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String,Object> getAllConsignerByClientname(){
        Map<String,Object> map = new HashMap<>();
        //添加值
        map.put("data",waybillServiceInter.getAllConsignerByClientname());
        map.put("index",1);
        //返回map集合
        return map;
    }


    /**
     * 根据发货人电话得到发货人的信息
     * @return 发货人集合
     */
    @PostMapping(value = "/getAllConsignerByPhone",produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String,Object> getAllConsignerByPhone(){
        Map<String,Object> map = new HashMap<>();
        map.put("index",0);
        map.put("data",waybillServiceInter.getAllConsignerByPhone());
        //返回map集合
        return map;
    }


    /**
     * 根据发货人id得到发货人的信息
     * @return 发货人对象
     */
    @PostMapping(value = "/getAllConsignerByConsignerId",produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String,Object> getAllConsignerByConsignerId(String id){
        Map<String,Object> map = new HashMap<>();
        map.put("type","发货人");
        map.put("data", waybillServiceInter.getAllConsignerByConsignerId(id));
        //返回map集合
        return map;

    }


    /**
     * 新增收货地区
     * @param request 请求
     * @return 是否成功
     */
    @PostMapping(value = "/insertConsigneeTmsRegion",produces = "application/json;charset=utf-8")
    @ResponseBody
    public String insertConsigneeTmsRegion(String xiangxi, HttpServletRequest request){
        //根据字符串分割
        String[] split = xiangxi.split("-");
        //判断是修改时未改动数据
        if (split.length==1){
            //将详细地址传参数
            TmsRegion existConsignerArea = waybillServiceInter.isExistConsignerArea(xiangxi);
            //判断收货人地址是否为空
            if (existConsignerArea==null){
                //实例化地区工具类
                RegionUtil util=new RegionUtil();
                //根据详细地址查询到地区信息
                TmsRegion tmsRegion = util.getTmsRegion(xiangxi);
                //将准备新增的地区id设置到seseion
                request.getSession().setAttribute("insertConsigneeTmsRegion",tmsRegion.getRegionId());
                //新增地址
                waybillServiceInter.insertTmsRegion(tmsRegion);
                //返回
                return "成功";
            }
            //将查询过后的id设置到session中
            request.getSession().setAttribute("insertConsigneeTmsRegion",existConsignerArea.getRegionId());
            return "成功";
        }else {
            //实例化地区模型类
            TmsRegion tmsRegion=new TmsRegion();
            //得到详细地址
            String id=tmsRegion.getDetailedAddress();
            //将详细地址传参数
            TmsRegion existConsignerArea = waybillServiceInter.isExistConsignerArea(split[0]+split[1]+split[2]+split[3]);
            //判断是否为空（不为空就是存在的直接查询到）
            if (existConsignerArea==null){
                //将uuid设置为id;
                tmsRegion.setRegionId(UuidUtil.getUuid());
                //设置省
                tmsRegion.setProvince(split[0]);
                //设置市
                tmsRegion.setCity(split[1]);
                //设置区
                tmsRegion.setDistrict(split[2]);
                //设置详细地址
                tmsRegion.setDetailedAddress(split[0]+split[1]+split[2]+split[3]);
                //将新增过后的id设置到session中
                request.getSession().setAttribute("insertConsigneeTmsRegion",tmsRegion.getRegionId());
                //判断是否成功
                if (waybillServiceInter.insertTmsRegion(tmsRegion)>0){
                    return "成功";
                }
                return "失败";
            }else {
                request.getSession().setAttribute("insertConsigneeTmsRegion",existConsignerArea.getRegionId());
                return "成功";
            }
        }
    }


    /**
     * 新增发货地区
     * @param request 请求
     * @return 是否成功
     */
    @PostMapping(value = "/insertConsignerTmsRegion",produces = "application/text;charset=utf-8")
    @ResponseBody
    public String insertConsignerTmsRegion(String xiangxi, HttpServletRequest request){
        //根据字符串分割
        String[] split = xiangxi.split("-");
        //判断修改时未更改数据
        if (split.length==1){
            //将详细地址传参数
            TmsRegion existConsignerArea = waybillServiceInter.isExistConsignerArea(xiangxi);
            //判断收货人地址是否为空
            if (existConsignerArea==null){
                //实例化地区工具类
                RegionUtil util=new RegionUtil();
                //根据详细地址查询到地区信息
                TmsRegion tmsRegion = util.getTmsRegion(xiangxi);
                //将准备新增的地区id设置到seseion
                request.getSession().setAttribute("insertConsigneeTmsRegion",tmsRegion.getRegionId());
                //新增地址
                waybillServiceInter.insertTmsRegion(tmsRegion);
                //返回
                return "成功";
            }
            //将查询过后的id设置到session中
            request.getSession().setAttribute("insertConsignerTmsRegion",existConsignerArea.getRegionId());
            //返回成功
            return "成功";
        }else {
            //实例化地区模型类
            TmsRegion tmsRegion=new TmsRegion();
            //得到详细地址
            String id=tmsRegion.getDetailedAddress();
            //将详细地址传参数
            TmsRegion existConsignerArea = waybillServiceInter.isExistConsignerArea(id);
            if (existConsignerArea==null) {
                //设置id
                tmsRegion.setRegionId(UuidUtil.getUuid());
                //设置省
                tmsRegion.setProvince(split[0]);
                //设置市
                tmsRegion.setCity(split[1]);
                //设置区
                tmsRegion.setDistrict(split[2]);
                //设置详细地址
                tmsRegion.setDetailedAddress(split[0]+split[1]+split[2]+ split[3]);
                //将新增过后的id设置到session中
                request.getSession().setAttribute("insertConsignerTmsRegion",tmsRegion.getRegionId());
                //判断是否成功
                if (waybillServiceInter.insertTmsRegion(tmsRegion)>0){
                    return "成功";
                }
                return "失败";
            }else {
                request.getSession().setAttribute("insertConsignerTmsRegion",existConsignerArea.getRegionId());
                return "成功";
            }
        }
    }


    /**
     * 从session中取出账号
     * @param request 请求
     * @return 用户信息
     */
    @PostMapping(value = "/getUserAccount",produces = "application/json;charset=utf-8")
    @ResponseBody
    public TmsUser getUserAccount(HttpServletRequest request){
        //得到登录人员的信息
        TmsUser login=(TmsUser) request.getSession().getAttribute("TMS_User");
        return login;
    }


    /**
     * 新增发货人
     * @param consigner 发货人信息
     * @param request 请求
     */
    @PostMapping(value = "/insertConsigner",produces = "application/text;charset=utf-8")
    @ResponseBody
    public void insertConsigner(Consigner consigner,HttpServletRequest request){
        //得到发货人信息调用方法
        Consigner existConsigner = waybillServiceInter.isExistConsigner(consigner);
        //判断发货人是否存在
        if (existConsigner==null){
            //不存在的话新增
            //得到之前存到session中的地区id
            String id=(String)request.getSession().getAttribute("insertConsignerTmsRegion");
            //设置发货人的地区id
            consigner.setRegionId(id);
            //设置发货人的id
            consigner.setConsignerId(UuidUtil.getUuid());
            //新增发货人
            waybillServiceInter.insertConsigner(consigner);
            //将发货人的id存到session
            request.getSession().setAttribute("isExistConsigner",consigner.getConsignerId());
        }else {
            //存在就将发货人的id存到session
            request.getSession().setAttribute("isExistConsigner",existConsigner.getConsignerId());
        }
    }


    /**
     * 新增收货人
     * @param consignee 发货人信息
     * @param request 请求
     */
    @PostMapping(value = "/insertConsignee",produces = "application/text;charset=utf-8")
    @ResponseBody
    public void insertConsignee(Consignee consignee,HttpServletRequest request){
        //得到收货人信息调用方法
        Consignee existConsigner = waybillServiceInter.isExistConsignee(consignee);
        //判断收货人是否存在
        if (existConsigner==null){
            //不存在的话新增
            //得到之前存到session中的地区id
            String id=(String)request.getSession().getAttribute("insertConsigneeTmsRegion");
            //设置收货人的地区id
            consignee.setRegionId(id);
            //设置收货人的id
            consignee.setConsigneeId(UuidUtil.getUuid());
            //新增收货人
            waybillServiceInter.insertConsignee(consignee);
            //将收货人的id存到session
            request.getSession().setAttribute("isExistConsigner",consignee.getConsigneeId());
        }else {
            //存在就将收货人的id存到session
            request.getSession().setAttribute("isExistConsignee",existConsigner.getConsigneeId());
        }
    }

    /**
     * 新增货运信息
     * @param freightinformationTable 货运信息
     * @param request 请求
     * @param uid 用户id
     * @return
     */
    @PostMapping(value = "/insertFreightinformation",produces = "application/text;charset=utf-8")
    @ResponseBody
    public String insertFreightinformation(FreightinformationTable freightinformationTable, HttpServletRequest request, String uid){
        //得到uuid
        String id=UuidUtil.getUuid();
        //设置到准备新增的模型类中
        freightinformationTable.setFreightinformationId(id);
        //得到用户id并设置到货运信息中
        freightinformationTable.setSalesman(uid);
        //将id设置到session中
        request.getSession().setAttribute("insertFreightinformation", freightinformationTable.getFreightinformationId());
        //设置id
        String cid=UuidUtil.getUuid();
        //实例化费用详细模型类
        Costbreakdown costbreakdown=new Costbreakdown();
        //设置id
        costbreakdown.setCostbreakdownId(cid);
        //设置现收
        costbreakdown.setRealizefee(freightinformationTable.getNowclosed());
        //设置应该收入的总金额
        costbreakdown.setReceivables(freightinformationTable.getAggregateamount());
        //未结清
        costbreakdown.setOwefee(freightinformationTable.getAggregateamount()-freightinformationTable.getNowclosed());
        //新增
        waybillServiceInter.insertCostbreakdown(costbreakdown);
        //将费用详细id设置到session中
        request.getSession().setAttribute("cid",cid);
        //判断是否成功
        if (waybillServiceInter.insertFreightinformation(freightinformationTable)>0){
            return "成功";
        }
        return "失败";
    }

    /**
     * 新增运单信息
     * @param waybill 运单信息
     * @param request 请求
     * @return 影响行数
     */
    @PostMapping(value = "/insertWaybill",produces = "application/text;charset=utf-8")
    @ResponseBody
    public String insertWaybill(Waybill waybill,HttpServletRequest request){

        System.out.println(waybill.getWaybillId());


        //收货人id
        String isExistConsignee=(String)request.getSession().getAttribute("isExistConsignee");
        //发货人id
        String isExistConsigner=(String)request.getSession().getAttribute("isExistConsigner");
        //收货地区
        String insertConsigneeTmsRegion=(String)request.getSession().getAttribute("insertConsigneeTmsRegion");
        //发货地区
        String insertConsignerTmsRegion=(String)request.getSession().getAttribute("insertConsignerTmsRegion");
        //货运信息
        String insertFreightinformation=(String)request.getSession().getAttribute("insertFreightinformation");
        //设置收货人id
        waybill.setConsigneeId(isExistConsignee);
        //设置发货人id
        waybill.setConsignerId(isExistConsigner);
        //设置收货地区
        waybill.setHarvestaddress(insertConsigneeTmsRegion);
        //设置发货地区
        waybill.setShipaddress(insertConsignerTmsRegion);
        //设置到模型类中
        waybill.setFreightinformation(insertFreightinformation);
        //从session中得到id
        String cid=(String)request.getSession().getAttribute("cid");
        //实例化
        Finance finance=new Finance();
        //设置财务id
        finance.setFinance(UuidUtil.getUuid());
        //从session的id设置到方法中
        finance.setCostbreakdownId(cid);
        //设置类型运输订单
        finance.setOrdertype("运输订单");
        //得到运单id并且设置
        finance.setOrdernumber(waybill.getWaybillId());
        //根据id查询费用信息
        Costbreakdown costbreakdownById = waybillServiceInter.getCostbreakdownById(cid);
        //根据值设置财务状态
        if (Double.doubleToLongBits(costbreakdownById.getReceivables())==Double.doubleToLongBits(costbreakdownById.getRealizefee())){
            //运单状态为已结清
            finance.setOrderstatus("已结清");
        }else if (Double.doubleToLongBits(costbreakdownById.getReceivables())>Double.doubleToLongBits(costbreakdownById.getRealizefee())){
            //运单状态为未结清
            finance.setOrderstatus("未结清");
        }else{
            //运单状态为未付款
            finance.setOrderstatus("未付款");
        }
        finance.setVerification("false");
        //新增财务管理
       waybillServiceInter.insertFinance(finance);
        //新增运单信息
        waybillServiceInter.insertWaybill(waybill);
        //新增运单状态
        waybillServiceInter.insertWaybillState(waybill.getWaybillId());
        Tailafter tailafter=new Tailafter();
        //设置跟踪信息的id
        tailafter.setTailafter(UuidUtil.getUuid());
        //获得当前时间
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//可以方便地修改日期格式
        String hehe = dateFormat.format( now );
        //设置跟踪时间
        tailafter.setTailafterTime(hehe);
        //设置运单号
        tailafter.setWaybillId(waybill.getWaybillId());
        //设置状态
        tailafter.setState("未装载");
        //选择跟踪信息
        xclTailAfter.insertXclTailAfter(tailafter);
        return "成功";
    }

}
